﻿using UnityEngine;

public static partial class Utility
{

    /// <summary>
    /// 值类型工具库
    /// </summary>
    public static class Value
    {

        /// <summary>
        /// 转换为数字单位文本
        /// </summary>
        /// <param name="value">要转换的数字</param>
        /// <param name="decimals">保留小数范围</param>
        /// <param name="ignoreValue">在正负值范围内忽略转换</param>
        /// <param name="unitScale">单位转换比例</param>
        /// <param name="valueUnits">值单位组</param>
        /// <returns></returns>
        public static string FormatUnitString(long value, string foramt, float ignoreValue, int unitScale, string[] valueUnits)
        {
            if (-ignoreValue < value && value < ignoreValue)
            {
                return value.ToString();
            }

            long[] parameter = UnitScale(value, unitScale, valueUnits, out bool isNegative);
            value = System.Math.Abs(value);
            double resultValue = value / (float)parameter[1];
#if UNITY_WEBGL
            resultValue = System.Math.Round(resultValue,2);
#endif
            var valueUnit = valueUnits[parameter[0]].FormatLocalize();
            string resultStr = isNegative ? "-" : string.Empty;
            resultStr += resultValue.ToString(foramt) + valueUnit;
            return resultStr;
        }

        static long[] UnitScale(long value, int unitScale, string[] valueUnits, out bool isNegative)
        {
            isNegative = value < 0;
            value = System.Math.Abs(value);

            long idx = 0;
            long scale = unitScale;
            while (value / scale >= unitScale && idx < valueUnits.Length - 1)
            {
                idx++;
                scale *= unitScale;
            }

            return new long[2] { idx, scale };
        }
    }
}
